package com.basics.common.utils.ip;


import com.alibaba.fastjson.JSONObject;
import com.basics.common.utils.StringUtils;
import com.basics.common.utils.http.HttpUtils;
import com.basics.framework.config.BasicsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    public AddressUtils() {
    }

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        } else {
            if (BasicsConfig.isAddressEnabled()) {
                String rspStr = HttpUtils.sendPost("http://ip.taobao.com/service/getIpInfo.php", "ip=" + ip);
                if (StringUtils.isEmpty(rspStr)) {
                    log.error("获取地理位置异常 {}", ip);
                    return address;
                }

                JSONObject obj = JSONObject.parseObject(rspStr);
                JSONObject data = (JSONObject)obj.getObject("data", JSONObject.class);
                String region = data.getString("region");
                String city = data.getString("city");
                address = region + " " + city;
            }

            return address;
        }
    }
}

